package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.SysRole;
import com.docking.heylo.dao.entity.SysRoleExample;
import com.docking.heylo.dao.mapper.SysRoleMapper;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.service.ISysRoleService;
import com.docking.heylo.service.ISysUserService;
import com.docking.heylo.web.dto.SysRoleDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private ISysUserService userService;


    @Override
    public void saveRole(SysRoleDto role) {
        SysRoleExample example = new SysRoleExample();
        SysRoleExample.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(role.getRoleName())){
            criteria.andRoleNameEqualTo(role.getRoleName());
        }

        if(sysRoleMapper.countByExample(example) > 0){
            throw new GeneralException("角色已存在");
        }

        sysRoleMapper.insertSelective(new SysRole(){{
            setRoleName(role.getRoleName());
            setRemark(role.getRemark());
            setCrtAt(new Date());
            setCrtBy(ThreadContext.userId());
        }});
    }

    @Override
    public PageInfo<Map<String, Object>> roleList(SysRoleDto roleDto) {
        PageHelper.startPage(roleDto.getPageNumber(), roleDto.getSize());
        return new PageInfo<>(sysRoleMapper.roleList(roleDto.getRoleName()));
    }

    @Override
    public SysRole roleInfo(Integer id) {
        return sysRoleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void editRole(SysRoleDto roleDto) {
        sysRoleMapper.updateByPrimaryKeySelective(new SysRole(){{
            setUpdAt(new Date());
            setUpdBy(ThreadContext.userId());
            setRoleName(roleDto.getRoleName());
            setRemark(roleDto.getRemark());
            setId(roleDto.getId());
        }});
    }

    @Override
    public void delRole(Integer id) {
        // 验证角色是否正在被使用
        if(userService.countByRoleId(id) != 0){
            throw new GeneralException("角色正在被使用，无法删除");
        }
        sysRoleMapper.deleteByPrimaryKey(id);
    }



}
